package com.magus.project.yddemo.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.magus.framework.core.persistence.JpaSearchUtils;
import com.magus.framework.core.persistence.SearchFilter;
import com.magus.framework.core.util.collect.CollectionUtils;
import com.magus.framework.core.util.lang.DateUtils;
import com.magus.framework.core.util.lang.StringUtils;
import com.magus.framework.system.entity.Company;
import com.magus.framework.system.util.SecurityUtils;
import com.magus.project.yddemo.entity.IndicatorMapperConfig;
import com.magus.project.yddemo.entity.IndicatorMapperData;
import com.magus.project.yddemo.entity.IndicatorMapperDataLog;
import com.magus.project.yddemo.vobean.IndicatorDataBean;
import com.magus.project.yddemo.vobean.IndicatorMapperDataBean;
import com.magus.project.yddemo.vobean.IndicatorsBean;

/**
 * 
 * 
 * @author Zhang JiaWei
 * @date 2018-03-23 16:13
 */
@Service
public class IndicatorMapperDataApiService {

	@Autowired
	@Qualifier("indicatorMapperDataApi")
	private RestTemplate restApi;

	@Autowired
	private IndicatorMapperConfigService configService;

	@Autowired
	private IndicatorMapperDataService dataService;

	@Autowired
	private IndicatorMapperDataLogService logService;

	@Autowired
	private IndicatorMapperReport1Service report1Service;

	/**
	 * 更新指标数据
	 */
	public void updateIndicatorData(String date) {

		// 获取所有指标配置信息
		List<IndicatorMapperConfig> allIndicators = configService.findAll();
		// 按电厂分组
		Map<Company, List<IndicatorMapperConfig>> plant_group = allIndicators.stream()
				.collect(Collectors.groupingBy(IndicatorMapperConfig::getCompany));

		// 按电厂分组获取各指标数据
		plant_group.entrySet().parallelStream().forEach(entry -> {

			// 生成日志
			IndicatorMapperDataLog log = new IndicatorMapperDataLog();
			log.setCompany(entry.getKey());
			log.setUpdateTime(System.currentTimeMillis());
			log.setOpUserName(SecurityUtils.getCurrentUser().getUserName());
			log.setSuccess(Boolean.TRUE);

			long t1 = System.currentTimeMillis();
			// 获取数据
			List<IndicatorMapperConfig> indicators = entry.getValue();
			Set<String> indicatorNames = indicators.stream().map(IndicatorMapperConfig::getCode)
					.collect(Collectors.toSet());

			Map<String, Object> params = new HashMap<>();
			params.put("date", date);
			params.put("indicator", StringUtils.join(indicatorNames, ","));

			ResponseEntity<IndicatorMapperDataBean> result = restApi.getForEntity(
					"/restful/x3/getIndicators?date={date}&indicator={indicatorNames}", IndicatorMapperDataBean.class,
					params);
			if (result.getStatusCode().is2xxSuccessful()) {
				String[] parsePatterns = { "yyyyMMddHHmm", "yyyyMMddHH", "yyyyMMdd", "yyyyMM" };
				Date time;

				// 保存OR更新数据
				IndicatorMapperDataBean datas = result.getBody();
				IndicatorsBean indicatorsBean = datas.getIndicators();
				try {
					time = DateUtils.parseDate(indicatorsBean.getIndicatorDate(), parsePatterns);
				} catch (ParseException e) {
					log.setSuccess(Boolean.FALSE);
					log.setLogInfo("错误的时间格式：" + indicatorsBean.getIndicatorDate());
					logService.save(log);
					return;
				}
				List<IndicatorDataBean> indicatorDatas = indicatorsBean.getIndicatorData();
				if (CollectionUtils.isNotEmpty(indicatorDatas)) {
					// 获取旧数据
					List<SearchFilter> searchFilters = new ArrayList<>();
					searchFilters.add(SearchFilter.in("indicatorCode", indicatorNames));
					searchFilters.add(SearchFilter.equal("date", date));
					Specification<IndicatorMapperData> spec = JpaSearchUtils.buildAndSpec(searchFilters);
					List<IndicatorMapperData> oldDatas = dataService.findAll(spec);

					// 保存新数据
					List<IndicatorMapperData> newDatas = new ArrayList<>();
					indicatorDatas.forEach(data -> {
						IndicatorMapperData newData = new IndicatorMapperData();
						newData.setIndicatorCode(data.getId());
						newData.setValue(data.getData());
						newData.setTime(time.getTime());
						newDatas.add(newData);
					});
					dataService.save(newDatas);

					// 删除旧数据
					dataService.delete(oldDatas);
				}
				long t2 = System.currentTimeMillis();
				log.setUseTime(t2 - t1);
				logService.save(log);
				// 刷新报表
				report1Service.updateDatas(time.getTime());
			} else {
				// 记录日志
				log.setSuccess(Boolean.FALSE);
				log.setLogInfo("请求数据失败：" + result.getStatusCode());
				logService.save(log);
			}
		});

	}

	public void updateDataByPlant(String date, Company plant) {
		// 生成日志
		IndicatorMapperDataLog log = new IndicatorMapperDataLog();
		log.setCompany(plant);
		log.setUpdateTime(System.currentTimeMillis());
		log.setOpUserName(SecurityUtils.getCurrentUser().getUserName());
		log.setSuccess(Boolean.TRUE);
		long t1 = System.currentTimeMillis();

		Specification<IndicatorMapperConfig> spec_c = JpaSearchUtils.buildAndSpec(SearchFilter.equal("company", plant));
		List<IndicatorMapperConfig> indicators = configService.findAll(spec_c);

		Set<String> indicatorNames = indicators.stream().map(IndicatorMapperConfig::getCode)
				.collect(Collectors.toSet());
		Map<String, Object> params = new HashMap<>();
		params.put("date", date);
		params.put("indicator", StringUtils.join(indicatorNames, ","));

		ResponseEntity<IndicatorMapperDataBean> result = restApi.getForEntity(
				"/restful/x3/getIndicators?date={date}&indicator={indicatorNames}", IndicatorMapperDataBean.class,
				params);

		if (result.getStatusCode().is2xxSuccessful()) {
			String[] parsePatterns = { "yyyyMMddHHmm", "yyyyMMddHH", "yyyyMMdd", "yyyyMM" };

			// 保存OR更新数据
			IndicatorMapperDataBean datas = result.getBody();
			IndicatorsBean indicatorsBean = datas.getIndicators();
			Date time;
			try {
				time = DateUtils.parseDate(indicatorsBean.getIndicatorDate(), parsePatterns);
			} catch (ParseException e) {
				log.setSuccess(Boolean.FALSE);
				log.setLogInfo("错误的时间格式：" + indicatorsBean.getIndicatorDate());
				logService.save(log);
				return;
			}
			List<IndicatorDataBean> indicatorDatas = indicatorsBean.getIndicatorData();
			if (CollectionUtils.isNotEmpty(indicatorDatas)) {
				// 获取旧数据
				List<SearchFilter> searchFilters = new ArrayList<>();
				searchFilters.add(SearchFilter.in("indicatorCode", indicatorNames));
				searchFilters.add(SearchFilter.equal("date", date));
				Specification<IndicatorMapperData> spec_d = JpaSearchUtils.buildAndSpec(searchFilters);
				List<IndicatorMapperData> oldDatas = dataService.findAll(spec_d);

				// 保存新数据
				List<IndicatorMapperData> newDatas = new ArrayList<>();
				indicatorDatas.forEach(data -> {
					IndicatorMapperData newData = new IndicatorMapperData();
					newData.setIndicatorCode(data.getId());
					newData.setValue(data.getData());
					newData.setTime(time.getTime());
					newDatas.add(newData);
				});
				dataService.save(newDatas);

				// 删除旧数据
				dataService.delete(oldDatas);
			}
			long t2 = System.currentTimeMillis();
			log.setUseTime(t2 - t1);
			logService.save(log);
			// 刷新报表
			report1Service.updateDatas(time.getTime());
		} else {
			// 记录日志
			log.setSuccess(Boolean.FALSE);
			log.setLogInfo("请求数据失败：" + result.getStatusCode());
			logService.save(log);
		}
	}

}
